package com.drcoffee.drcoffeemall.util;

import org.redisson.Redisson;
import org.redisson.api.RAtomicLong;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.Date;

/*
 * 编号生成工具类
 * */
@Repository
public class GenerateCodeUtil {

    final
    RedisTemplate<String, Object> redisTemplate;
    private final Redisson redisson;   // 注入Redisson对象

    public GenerateCodeUtil(RedisTemplate<String, Object> redisTemplate, Redisson redisson) {
        this.redisTemplate = redisTemplate;
        this.redisson = redisson;
    }

    /*
     * 生成编号
     * */
    public String generate(String PREFIX) {
        RAtomicLong atomicLong = redisson.getAtomicLong("code_generate");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());
        String prefix_code = PREFIX + currentDate;
        long counter = atomicLong.incrementAndGet();
        String counterFormatted = String.format("%03d", counter + 1);
        prefix_code += counterFormatted;
        return prefix_code;
    }
}
